package com.example.roam.game.dujiangyan.game.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;

import com.example.roam.game.dujiangyan.game.control.GameControl;

public class GameUI extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder surfaceHolder;
    private Paint paint;
    private GameControl gameControl;

    public GameUI(Context context) {
        super(context);
        initView();
        initGame();
    }

    public GameUI(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
        initGame();
    }

    public GameUI(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
        initGame();
    }

    public void initView(){
        surfaceHolder = this.getHolder();
        surfaceHolder.addCallback(this);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.LTGRAY);
        gameControl = new GameControl(this.getContext());
    }

    public void initGame(){

    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        Runner runner = new Runner();
        runner.start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    class Runner extends Thread{
        @Override
        public void run() {
            while (!gameControl.isFinsh()){
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                draw();
            }
        }
    }

    public void draw(){
        Canvas canvas = surfaceHolder.lockCanvas();
        canvas.drawRect(new Rect(0,0,1080,1793),paint);
        gameControl.draw(canvas);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch ( event.getAction() ){
            case MotionEvent.ACTION_DOWN:
                gameControl.onTouchDot(event);
                break;
        }

        return true;
    }

    public GameControl getGameControl() {
        return gameControl;
    }
}
